﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Viettel.VOFFICE.DAO.DAL.Paging;
using Viettel.VOFFICE.DAO.Models;

namespace Viettel.VOFFICE.DAO.DAL.Repository
{
    /// <summary>
    /// lưu các thông tin có tính chất key-value ít ảnh hưởng đến hệ thống
    /// </summary>
    public class MetaDataRepository : IRepository<MetaData>
    {
        private VOFFICEContext context;
        public MetaDataRepository(VOFFICEContext context)
        {
            if (context == null)
            {
                throw new Exception("Context must be init");
            }
            this.context = context;
        }
        public IEnumerable<MetaData> Get()
        {
            return context.MetaDatas.OrderByDescending(o => o.UpdatedAt).Select(o => o);
        }

        public MetaData GetById(object id)
        {
            return context.MetaDatas.Find(int.Parse(id.ToString()));
        }

        public IEnumerable<MetaData> FindByName(object s)
        {
            throw new NotImplementedException();
        }

        public void Insert(MetaData T)
        {
            context.MetaDatas.Add(T);
            Save();
        }

        public void Delete(object id)
        {
            var item = GetById(id);
            if (item != null)
            {
                context.MetaDatas.Attach(item);
                context.MetaDatas.Remove(item);
                Save();
            }
        }


        public void Delete(MetaData T)
        {
            if (null != T)
            {
                context.MetaDatas.Attach(T);
                context.MetaDatas.Remove(T);
                Save();
            }
        }
        public void Update(MetaData T)
        {
            context.Entry(T).State = EntityState.Modified;
            Save();
        }

        public void Save()
        {
            context.SaveChanges();
        }


        public IEnumerable<MetaData> GetAllItemParentID(int parentID)
        {
            switch (parentID)
            {
                case 0:
                    return context.MetaDatas.Where(o => o.ParentId == parentID).OrderByDescending(o => o.CreatedAt).Select(o => o);
                default:
                    return null;
            }
        }

        public IEnumerable<MetaData> GetAllItemChildID(int childId)
        {
            if (childId != 0)
            {
                return
                    context.MetaDatas.Where(o => o.ParentId == childId).OrderByDescending(o => o.CreatedAt).Select(
                        o => o);
            }
            return null;
        }

        public PagedList<MetaData> GetPaging(int pageSize, int pageIndex)
        {
            return context.MetaDatas.OrderByDescending(o => o.UpdatedAt).Paginate(pageIndex, pageSize);
        }


    }
}
